#include <iostream>
#include <opencv2/opencv.hpp>
#include "Camera.h"
#include "CameraCalibration.h"
#include "ObjectRecognition.h"

int main() {
    // 相机标定部分
    std::string calibrationImagePath = "path/to/calibration/images";  // 替换为实际的标定图像文件夹路径
    cv::Size chessboardSize(9, 6);  // 棋盘格内角点数（行，列）
    float squareSize = 25.0;   // 棋盘格方块尺寸（毫米）

    CameraCalibration calibration(calibrationImagePath, chessboardSize, squareSize);
    if (!calibration.performCalibration()) {
        std::cerr << "Camera calibration failed." << std::endl;
        return -1;
    }

    cv::Mat cameraMatrix = calibration.getCameraMatrix();
    cv::Mat distortionCoefficients = calibration.getDistortionCoefficients();

    // 打开相机
    Camera camera(0);
    if (!camera.openCamera()) {
        std::cerr << "Failed to open camera." << std::endl;
        return -1;
    }

    // 物体识别部分
    std::string classifierPath = "path/to/haar_cascade.xml";  // 替换为实际的 Haar 级联分类器文件路径
    ObjectRecognition recognizer(classifierPath);
    if (!recognizer.initialize()) {
        std::cerr << "Failed to initialize object recognizer." << std::endl;
        return -1;
    }

    cv::Mat frame;
    while (true) {
        // 捕获一帧图像
        camera.captureFrame();
        frame = camera.getFrame();

        if (frame.empty()) {
            std::cerr << "Failed to capture frame." << std::endl;
            break;
        }

        // 图像校正
        cv::Mat undistortedFrame;
        cv::undistort(frame, undistortedFrame, cameraMatrix, distortionCoefficients);

        // 物体识别
        std::vector<cv::Rect> detectedObjects = recognizer.recognize(undistortedFrame);

        // 在图像上绘制检测结果
        for (const auto& rect : detectedObjects) {
            cv::rectangle(undistortedFrame, rect, cv::Scalar(0, 255, 0), 2);
        }

        // 显示图像
        cv::imshow("Object Recognition", undistortedFrame);

        // 按 'q' 键退出循环
        if (cv::waitKey(1) == 'q') {
            break;
        }
    }

    // 释放资源
    cv::destroyAllWindows();

    return 0;
}